package com.common.base.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.CallSuper;
import androidx.appcompat.widget.SwitchCompat;
import androidx.core.content.ContextCompat;
import com.common.CommonApplication;
import com.common.R;
import com.common.bean.InfoResult;
import com.common.bean.MsgBean;
import com.common.theme.ColorPalette;
import com.common.theme.Theme;
import com.common.theme.ThemeHelper;
import com.common.theme.Themed;
import com.common.theme.UiElementInizializer;
import com.common.theme.ViewUtil;
import com.common.ui.alerter.Alerter;
import com.common.ui.alerter.OnHideAlertListener;
import com.common.ui.alerter.OnShowAlertListener;
import com.common.ui.barlibrary.ImmersionBar;
import com.common.ui.barlibrary.OSUtils;
import com.common.ui.loadsir.callback.Callback;
import com.common.ui.loadsir.callback.EmptyCallback;
import com.common.ui.loadsir.callback.ErrorCallback;
import com.common.ui.loadsir.callback.LoadingCallback;
import com.common.ui.loadsir.callback.SuccessCallback;
import com.common.ui.loadsir.callback.TimeoutCallback;
import com.common.ui.loadsir.core.Convertor;
import com.common.ui.loadsir.core.LoadService;
import com.common.ui.loadsir.core.LoadSir;
import com.common.ui.swipebacklayout.lib.SwipeBackLayout;
import com.common.ui.swipebacklayout.lib.app.SwipeBackActivity;
import com.common.utils.ApkUtils;
import com.mikepenz.iconics.IconicsDrawable;
import com.mikepenz.iconics.typeface.IIcon;
import com.orhanobut.hawk.Hawk;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.ArrayList;
import butterknife.ButterKnife;

public abstract class BaseThemeActivity extends SwipeBackActivity implements UiElementInizializer {

    private static final int SUCCESS_CODE = 0x00;
    private static final int ERROR_CODE = 0x01;
    private ActivityManager activityManager = ActivityManager.getActivityManager();
    private EventBus eventBus;
    private Toast toast = null;
    private SwipeBackLayout swipeBackLayout;
    private InputMethodManager inputMethodManager;
    private ThemeHelper themeHelper;
    private boolean coloredNavBar;//虚拟导航栏是否有颜色
    private boolean obscuredStatusBar;//是否全透明导航栏
    private boolean applyThemeSingleImgAct;
    private boolean customIconColor;
    private LoadService loadService;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            CommonApplication.getInstance().finishActivity(this);
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (null != activityManager) {
            activityManager.putActivity(this);
        }
        themeHelper = ThemeHelper.getInstanceLoaded(getApplicationContext());
        //初始化沉浸式
        initImmersionBar();
        //把设置布局文件的操作交给继承的子类
        setContentView(getLayoutResId());
        ButterKnife.bind(this);
        setScreenVertical(this);
        initSwipeBack();
        eventBus = EventBus.getDefault();
        eventBus.register(this);
        if (isSupportLoadSirEnabled() != null) {
            initLoadSir(isSupportLoadSirEnabled());
        }
        init();
        loadData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 非必加
        // 如果你的app可以横竖屏切换，适配了华为emui3系列系统手机，并且navigationBarWithEMUI3Enable为true，
        // 请在onResume方法里添加这句代码（同时满足这三个条件才需要加上代码哦：1、横竖屏可以切换；2、华为emui3系列系统手机；3、navigationBarWithEMUI3Enable为true）
        // 否则请忽略
        if (OSUtils.isEMUI3_x() && isImmersionBarEnabled()) {
            ImmersionBar.with(this).init();
        }
        updateTheme();
        updateUiElements();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (isImmersionBarEnabled()) {
            // 非必加
            // 如果你的app可以横竖屏切换，适配了4.4或者华为emui3.1系统手机，并且navigationBarWithKitkatEnable为true，
            // 请务必在onConfigurationChanged方法里添加如下代码（同时满足这三个条件才需要加上代码哦：1、横竖屏可以切换；2、android4.4或者华为emui3.1系统手机；3、navigationBarWithKitkatEnable为true）
            // 否则请忽略
            ImmersionBar.with(this).init();
        }
    }

    @Override
    public void finish() {
        super.finish();
        hideSoftKeyBoard();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        inputMethodManager = null;
        if (eventBus != null) {
            eventBus.unregister(this);
        }
        if (null != activityManager) {
            activityManager.removeActivity(this);
        }
    }

    public void updateTheme() {
        themeHelper.updateTheme();
        coloredNavBar = Hawk.get(getString(R.string.preference_colored_nav_bar), false);
        obscuredStatusBar = Hawk.get(getString(R.string.preference_translucent_status_bar), true);
        applyThemeSingleImgAct = Hawk.get("apply_theme_img_act", true);
        customIconColor = Hawk.get(getString(R.string.preference_custom_icon_color), false);
    }

    @CallSuper
    @Override
    public void updateUiElements() {
        for (View view : ViewUtil.getAllChildren(findViewById(android.R.id.content))) {
            if (view instanceof Themed) ((Themed) view).refreshTheme(getThemeHelper());
        }
    }

    /**
     * 设置Activity的显示方向为横向
     *
     * @param activity
     */
    @SuppressLint("SourceLockedOrientationActivity")
    private void setScreenHorizontal(Activity activity) {
        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }

    /**
     * 设置Activity的显示方向为垂直方向
     *
     * @param activity
     */
    @SuppressLint("SourceLockedOrientationActivity")
    private void setScreenVertical(Activity activity) {
        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    protected void initImmersionBar() {
        if (isImmersionBarEnabled()) {
            //在BaseThemeActivity里初始化
            ImmersionBar.with(this).navigationBarColor(R.color.barcolor).init();
        } else {
            //initSystemBarTint();
        }
    }

    private void initSwipeBack() {
        if (isSupportSwipeBackEnabled()) {
            // 可以调用该方法，设置是否允许滑动退出
            setSwipeBackEnable(true);
            swipeBackLayout = getSwipeBackLayout();
            // 设置滑动方向，可设置EDGE_LEFT, EDGE_RIGHT, EDGE_ALL, EDGE_BOTTOM
            swipeBackLayout.setEdgeTrackingEnabled(SwipeBackLayout.EDGE_LEFT);
            // 滑动退出的效果只能从边界滑动才有效果，如果要扩大touch的范围，可以调用这个方法
            //swipeBackLayout.setEdgeSize(200);
        } else {
            setSwipeBackEnable(false);
        }
    }

    private void initLoadSir(View loadSirView) {
        LoadSir loadSir = new LoadSir.Builder()
                .addCallback(new LoadingCallback())
                .addCallback(new TimeoutCallback())
                .addCallback(new EmptyCallback())
                .addCallback(new ErrorCallback())
                .setDefaultCallback(LoadingCallback.class)
                .build();
        loadService = loadSir.register(loadSirView, new Callback.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadService.showCallback(LoadingCallback.class);
                // 重新加载逻辑
            }
        }, new Convertor<InfoResult>() {
            @Override
            public Class<? extends Callback> map(InfoResult infoResult) {
                Class<? extends Callback> resultCode = SuccessCallback.class;
                switch (infoResult.getState()) {
                    //success
                    case SUCCESS_CODE:
                        if (infoResult.getState() == 1) {
                            resultCode = SuccessCallback.class;
                        } else {
                            resultCode = EmptyCallback.class;
                        }
                        break;
                    case ERROR_CODE:
                        resultCode = ErrorCallback.class;
                        break;
                    default:
                        resultCode = ErrorCallback.class;
                }
                return resultCode;
            }
        });
    }

    //===================================alerter==========================================
    public void showAlert(String msg) {
        Alerter.create(this)
                .setText(msg)
                .disableOutsideTouch()
                .setDuration(700)
                .show();
    }

    private void showAlertDefault() {
        Alerter.create(this)
                .setTitle("Alert Title")
                .setText("Alert text...")
                .disableOutsideTouch()
                .show();
    }

    private void showAlertColoured() {
        Alerter.create(this)
                .setTitle("Alert Title")
                .setText("Alert text...")
                .setBackgroundColor(R.color.colorAccent)
                .show();
    }

    private void showAlertWithIcon() {
        Alerter.create(this)
                .setText("Alert text...")
                .setIcon(R.drawable.alerter_ic_face)
                .show();
    }

    private void showAlertTextOnly() {
        Alerter.create(this)
                .setText("Alert text...")
                .show();
    }

    private void showAlertWithOnClick() {
        Alerter.create(this)
                .setTitle("Alert Title")
                .setText("Alert text...")
                .setDuration(10000)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Toast.makeText(BaseThemeActivity.this, "OnClick Called", Toast.LENGTH_LONG).show();
                    }
                })
                .show();
    }

    private void showAlertVerbose() {
        Alerter.create(BaseThemeActivity.this)
                .setTitle("Alert Title")
                .setText("The alert scales to accommodate larger bodies of text. " +
                        "The alert scales to accommodate larger bodies of text. " +
                        "The alert scales to accommodate larger bodies of text.")
                .show();
    }

    private void showAlertCallbacks() {
        Alerter.create(BaseThemeActivity.this)
                .setTitle("Alert Title")
                .setText("Alert text...")
                .setDuration(10000)
                .setOnShowListener(new OnShowAlertListener() {
                    @Override
                    public void onShow() {
                        Toast.makeText(BaseThemeActivity.this, "Show Alert", Toast.LENGTH_LONG).show();
                    }
                })
                .setOnHideListener(new OnHideAlertListener() {
                    @Override
                    public void onHide() {
                        Toast.makeText(BaseThemeActivity.this, "Hide Alert", Toast.LENGTH_LONG).show();
                    }
                })
                .show();
    }

    private void showAlertInfiniteDuration() {
        Alerter.create(BaseThemeActivity.this)
                .setTitle("Alert Title")
                .setText("Alert text...")
                .enableInfiniteDuration(true)
                .show();
    }

    /**
     * 跳转到权限设置界面
     */
    public void goIntentSetting() {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            intent.setAction(Intent.ACTION_VIEW);
            intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            intent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
        }
        startActivity(intent);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handlerMeg(MsgBean msgBean) {

    }

    public void showToast(String msg) {
        if (toast == null) {
            toast = Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT);
        } else {
            toast.setText(msg);
        }
        toast.show();
    }

    public int getColor(Context context, int id) {
        return ContextCompat.getColor(context, id);
    }

    public void hideSoftKeyBoard() {
        View localView = getCurrentFocus();
        if (this.inputMethodManager == null) {
            this.inputMethodManager = ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE));
        }
        if ((localView != null) && (this.inputMethodManager != null)) {
            this.inputMethodManager.hideSoftInputFromWindow(localView.getWindowToken(), 2);
        }
    }

    /**
     * 跳转到某个Activity
     *
     * @param activity
     * @param targetActivity
     */
    public void switchTo(Activity activity, Class<? extends Activity> targetActivity, boolean finish) {
        switchTo(activity, new Intent(activity, targetActivity), finish);
    }

    public void switchTo(Activity activity, Intent intent, boolean finish) {
        activity.startActivity(intent);
        if (finish) {
            finish();
        }
        //overridePendingTransition(R.anim.alpha_out, R.anim.alpha_in);
    }

    // -------------------- BaseActivity的辅助封装 --------------------- //
    public abstract boolean isImmersionBarEnabled();

    /**
     * 是否支持滑动返回
     *
     * @return
     */
    public abstract boolean isSupportSwipeBackEnabled();

    public abstract View isSupportLoadSirEnabled();

    /**
     * 返回当前Activity布局文件的id
     *
     * @return
     */
    public abstract int getLayoutResId();

    /**
     * 初始化的一些操作
     */
    public abstract void init();

    /**
     * 加载网络数据
     */
    public abstract void loadData();

    /**
     * 网络数据返回成功
     */
    protected abstract void onSuccess(int what, InfoResult t);

    /**
     * 网络数据返回失败
     */
    protected abstract void onFail(int what, InfoResult t);

    public EventBus getEventBus() {
        return eventBus;
    }

    public ThemeHelper getThemeHelper() {
        return themeHelper;
    }

    public void setThemeHelper(ThemeHelper themeHelper) {
        this.themeHelper = themeHelper;
    }

    public boolean isNavigationBarColored() {
        return coloredNavBar;
    }

    public boolean isTranslucentStatusBar() {
        return obscuredStatusBar;
    }

    public boolean themeOnSingleImgAct() {
        return applyThemeSingleImgAct;
    }

    protected boolean isTransparencyZero() {
        return true;
        /* return 255 - (getString(R.string.preference_transparency), 0) == 255;*/
    }

    protected void setScrollViewColor(ScrollView scr){
        themeHelper.setScrollViewColor(scr);
    }

    public int getTransparency() {
        return 0;
        /*return 255 - SP.getInt(getString(org.horaapps.leafpic.R.string.preference_transparency), 0);*/
    }

    public void setBaseTheme(Theme baseTheme) {
        themeHelper.setBaseTheme(baseTheme);
    }

    public void themeSeekBar(SeekBar bar) {
        themeHelper.themeSeekBar(bar);
    }

    public int getPrimaryColor() {
        return themeHelper.getPrimaryColor();
    }

    public int getAccentColor() {
        return themeHelper.getAccentColor();
    }

    public Theme getBaseTheme() {
        return themeHelper.getBaseTheme();
    }

    public int getBackgroundColor() {
        return themeHelper.getBackgroundColor();
    }

    protected Drawable getPlaceHolder() {
        return themeHelper.getPlaceHolder();
    }

    protected int getInvertedBackgroundColor() {
        return themeHelper.getInvertedBackgroundColor();
    }

    public int getTextColor() {
        return themeHelper.getTextColor();
    }

    public int getSubTextColor() {
        return themeHelper.getSubTextColor();
    }

    public int getCardBackgroundColor() {
        return themeHelper.getCardBackgroundColor();
    }

    public int getIconColor() {
        return themeHelper.getIconColor();
    }

    protected int getDrawerBackground() {
        return themeHelper.getDrawerBackground();
    }

    public int getDialogStyle() {
        return themeHelper.getDialogStyle();
    }

    protected int getPopupToolbarStyle() {
        return themeHelper.getPopupToolbarStyle();
    }

    protected ArrayAdapter<String> getSpinnerAdapter(ArrayList<String> items) {
        return themeHelper.getSpinnerAdapter(items);
    }

    protected int getDefaultThemeToolbarColor3th() {
        return themeHelper.getDefaultThemeToolbarColor3th();
    }

    public void themeRadioButton(RadioButton radioButton) {
        themeHelper.themeRadioButton(radioButton);
    }

    public void themeCheckBox(CheckBox chk) {
        themeHelper.themeCheckBox(chk);
    }

    protected void themeButton(Button btn) {
        themeHelper.themeButton(btn);
    }

    public void setSwitchColor(int color, SwitchCompat... sw) {
        for (SwitchCompat switchCompat : sw) {
            themeHelper.setSwitchCompactColor(switchCompat, color);
        }
    }

    public void setTextViewColor(int color, TextView... textViews) {
        for (TextView txt : textViews) {
            themeHelper.setTextViewColor(txt, color);
        }
    }

    public IconicsDrawable getToolbarIcon(IIcon icon) {
        return themeHelper.getToolbarIcon(icon);
    }

    protected void setStatusBarNavigationBarColor() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            int color = getThemeHelper().getPrimaryColor();
            if (isTranslucentStatusBar()) {
                ImmersionBar.with(this)
                        .statusBarDarkFont(false)   //状态栏字体是深色，不写默认为亮色
                        .navigationBarDarkIcon(false) //导航栏图标是深色，不写默认为亮色
                        .autoDarkModeEnable(true) //自动状态栏字体和导航栏图标变色，必须指定状态栏颜色和导航栏颜色才可以自动变色哦
                        .autoNavigationBarDarkModeEnable(true) //自动导航栏图标变色，必须指定导航栏颜色才可以自动变色哦
                        .autoStatusBarDarkModeEnable(true)//自动状态栏字体变色，必须指定状态栏颜色才可以自动变色哦
                        .statusBarColorForDecimal(ColorPalette.getObscuredColor(color))
                        //自动状态栏字体和导航栏图标变色，必须指定状态栏颜色和导航栏颜色才可以自动变色哦
                        .autoDarkModeEnable(true)
                        //解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                        .fitsSystemWindows(true)
                        .init();
            } else {
                ImmersionBar.with(this)
                        .statusBarDarkFont(false)   //状态栏字体是深色，不写默认为亮色
                        .navigationBarDarkIcon(false) //导航栏图标是深色，不写默认为亮色
                        .autoDarkModeEnable(true) //自动状态栏字体和导航栏图标变色，必须指定状态栏颜色和导航栏颜色才可以自动变色哦
                        .autoNavigationBarDarkModeEnable(true) //自动导航栏图标变色，必须指定导航栏颜色才可以自动变色哦
                        .autoStatusBarDarkModeEnable(true)//自动状态栏字体变色，必须指定状态栏颜色才可以自动变色哦
                        .statusBarColorForDecimal(color)
                        //自动状态栏字体和导航栏图标变色，必须指定状态栏颜色和导航栏颜色才可以自动变色哦
                        .autoDarkModeEnable(true)
                        //解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                        .fitsSystemWindows(true)
                        .init();
            }
            if (isNavigationBarColored()) {
                //getWindow().setNavigationBarColor(color);
                ImmersionBar.with(this)
                        .statusBarDarkFont(false)   //状态栏字体是深色，不写默认为亮色
                        .navigationBarDarkIcon(false) //导航栏图标是深色，不写默认为亮色
                        .autoDarkModeEnable(true) //自动状态栏字体和导航栏图标变色，必须指定状态栏颜色和导航栏颜色才可以自动变色哦
                        .autoNavigationBarDarkModeEnable(true) //自动导航栏图标变色，必须指定导航栏颜色才可以自动变色哦
                        .autoStatusBarDarkModeEnable(true)//自动状态栏字体变色，必须指定状态栏颜色才可以自动变色哦
                        //是否可以修改导航栏颜色，默认为true
                        .navigationBarEnable(true)
                        //导航栏颜色，不写默认黑色
                        .navigationBarColorForDecimal(color)
                        //自动状态栏字体和导航栏图标变色，必须指定状态栏颜色和导航栏颜色才可以自动变色哦
                        .autoDarkModeEnable(true)
                        //解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                        .fitsSystemWindows(true)
                        .init();

            } else {
                // getWindow().setNavigationBarColor(ContextCompat.getColor(this, R.color.md_black_1000));
                ImmersionBar.with(this)
                        .statusBarDarkFont(false)   //状态栏字体是深色，不写默认为亮色
                        .navigationBarDarkIcon(false) //导航栏图标是深色，不写默认为亮色
                        .autoDarkModeEnable(true) //自动状态栏字体和导航栏图标变色，必须指定状态栏颜色和导航栏颜色才可以自动变色哦
                        .autoNavigationBarDarkModeEnable(true) //自动导航栏图标变色，必须指定导航栏颜色才可以自动变色哦
                        .autoStatusBarDarkModeEnable(true)//自动状态栏字体变色，必须指定状态栏颜色才可以自动变色哦
                        //是否可以修改导航栏颜色，默认为true
                        .navigationBarEnable(true)
                        //导航栏颜色，不写默认黑色
                        .navigationBarColor(R.color.barcolor)
                        //自动状态栏字体和导航栏图标变色，必须指定状态栏颜色和导航栏颜色才可以自动变色哦
                        .autoDarkModeEnable(true)
                        //解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                        .fitsSystemWindows(true)
                        .init();
            }
            ApkUtils.getInstance().setAndroidNativeLightStatusBar(this,false);
            ApkUtils.getInstance().setLightNavigationBar(this,false);
        }
    }

    //================================= 方法 ==========================================

    /**
     * 5.0之后
     * 有权查看使用情况的应用(打开使用量数据访问)
     */
    public void openUsedApp(){
        Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
        startActivity(intent);
    }

    /**
     * 打开悬浮窗设置权限
     */
    private void requestSettingCanDrawOverlays() {
        int sdkInt = Build.VERSION.SDK_INT;
        if (sdkInt >= Build.VERSION_CODES.O) {
            //8.0以上
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
            startActivityForResult(intent, 2);
        } else if (sdkInt >= Build.VERSION_CODES.M) {//6.0-8.0
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivityForResult(intent, 2);
        } else {//4.4-6.0以下
            //无需处理了
        }
    }
}
